package com.grwx.omc.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.grwx.omc.admin.dao.SysLookupDetailMapper;
import com.grwx.omc.admin.entity.SysLookupDetail;
import com.grwx.omc.admin.service.ISysLookupDetailService;
import com.grwx.omc.constant.Constant;
import com.grwx.omc.exception.ValidationException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysLookupDetailServiceImpl extends ServiceImpl<SysLookupDetailMapper, SysLookupDetail>
        implements ISysLookupDetailService {

    @Resource
    private SysLookupDetailMapper sysLookupDetailMapper;

    @Override
    public IPage<SysLookupDetail> page(Page<SysLookupDetail> page, SysLookupDetail sysLookupDetail) {
        return sysLookupDetailMapper.pageList(page, sysLookupDetail);
    }

    @Override
    public void addOrUpdate(SysLookupDetail sysLookupDetail) {
        if (null == sysLookupDetail) {
            throw new ValidationException(Constant.MsgCode.EMPTY_PARAM);
        }
        // 字典类型编码唯一性校验
        uniqueCheck(sysLookupDetail);
        if (null == sysLookupDetail.getId()) {
            sysLookupDetail.preInsert();
            save(sysLookupDetail);
        } else {
            sysLookupDetail.preUpdate();
            updateById(sysLookupDetail);
        }
    }

    /**
     * typeCode唯一校验
     * 规则：同一字典类型下，字典数据名称和编码不能重复
     * @param sysLookupDetail
     */
    private void uniqueCheck(SysLookupDetail sysLookupDetail) {
        QueryWrapper<SysLookupDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("type_code", sysLookupDetail.getTypeCode());
        wrapper.and(Wrapper ->
                wrapper.eq("lookup_code", sysLookupDetail.getLookupCode())
                .or()
                .eq("lookup_name", sysLookupDetail.getLookupName()));
        List<SysLookupDetail> existLookupType = list(wrapper);
        if (!ObjectUtils.isEmpty(existLookupType)) {
            throw new ValidationException("omc.admin.lookup_detail.E001");
        }
    }


}
